import { useState, useEffect } from 'react'
import styled from 'styled-components'
import { Button, Tag, Table, Popconfirm, Modal, Form, Input, DatePicker, message } from 'antd'
import _ from '@/assets/utils'
import dayjs from 'dayjs'
import API from '@/api'

/* 组件样式 */
const TaskStyle = styled.div`
    box-sizing: border-box;
    margin: 0 auto;
    width: 800px;

    .header-box{
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 0;
        border-bottom: 1px solid #DDD;

        .title{
            font-size: 20px;
            font-weight: normal;
        }
    }

    .tag-box{
        margin: 15px 0;

        .ant-tag{
            padding: 5px 15px;
            margin-right: 15px;
            font-size: 14px;
            cursor: pointer;
        }
    }

    .ant-btn-link{
        padding: 4px 5px;
    }

    .ant-modal-header{
        margin-bottom: 20px;
    }
`

/* 组件视图 */
export default function Task() {
    // 定义表格列
    const columns = [{
        title: '编号',
        dataIndex: 'id',
        width: '6%',
        align: 'center'
    }, {
        title: '任务描述',
        dataIndex: 'task',
        width: '50%',
        ellipsis: true
    }, {
        title: '状态',
        dataIndex: 'state',
        width: '10%',
        align: 'center',
        render: text => +text === 1 ? '未完成' : '已完成'
    }, {
        title: '完成时间',
        width: '16%',
        align: 'center',
        render(text, record) {
            let { state, time, complete } = record
            time = +state === 1 ? time : complete
            return _.formatTime(time, '{1}/{2} {3}:{4}')
        }
    }, {
        title: '操作',
        width: '18%',
        render(text, record) {
            let { state, id } = record
            return <>
                <Popconfirm title="您确定要删除此任务吗?"
                    onConfirm={handleRemove.bind(null, id)}>
                    <Button type="link" danger>删除</Button>
                </Popconfirm>

                {+state === 1 ?
                    <Popconfirm title="您确定要把此任务设置为已完成吗?"
                        onConfirm={handleUpdate.bind(null, id)}>
                        <Button type="link">完成</Button>
                    </Popconfirm> :
                    null
                }
            </>
        }
    }]

    // 定义状态
    let [data, setData] = useState([]),
        [loading, setLoading] = useState(false),
        [selectedIndex, setSelectedIndex] = useState(0)
    let [modalVisible, setModalVisible] = useState(false),
        [confirmLoading, setConfirmLoading] = useState(false)
    let [formIns] = Form.useForm()

    // 第一次渲染完&每一次选中状态改变，都要从服务器重新获取数据
    useEffect(() => {
        initData()
    }, [selectedIndex])

    // 从服务器获取指定状态的任务
    const initData = async () => {
        setLoading(true)
        try {
            let { code, list } = await API.queryTaskList(selectedIndex)
            if (+code !== 0) list = []
            setData(list)
        } catch (_) { }
        setLoading(false)
    }

    // 关闭Modal对话框
    const closeModal = () => {
        setModalVisible(false)
        setConfirmLoading(false)
        // 清除表单信息及校验信息
        formIns.resetFields()
    }

    // 确认新增任务
    const submit = async () => {
        try {
            await formIns.validateFields()
            let { task, time } = formIns.getFieldsValue()
            // time：是基于dayjs构建的日期对象
            time = time.format('YYYY-MM-DD HH:mm:ss')
            // 向服务器发送请求
            setConfirmLoading(true)
            let { code } = await API.insertTaskInfo(task, time)
            if (+code === 0) {
                message.success('恭喜您，新增成功~')
                closeModal()
                // 从服务器获取最新的任务列表
                initData()
            } else {
                message.error('很遗憾，新增失败，请稍后再试~')
            }
        } catch (_) { }
        setConfirmLoading(false)
    }

    // 删除任务
    const handleRemove = async (id) => {
        try {
            let { code } = await API.removeTaskById(id)
            if (+code === 0) {
                message.success('恭喜您，删除成功')
                // 让客户端页面中的数据也跟着删除
                // initData()
                let arr = data.filter(item => +item.id !== +id)
                setData(arr)
                return
            }
            message.error('很遗憾，删除失败，请稍后再试')
        } catch (_) { }
    }

    // 修改任务
    const handleUpdate = async (id) => {
        try {
            let { code } = await API.updateTaskById(id)
            if (+code === 0) {
                message.success('恭喜您，修改成功')
                // 让页面中的数据也会跟着变
                let arr = data.map(item => {
                    if (+item.id === +id) {
                        item.state = 2
                        item.complete = dayjs().format('YYYY-MM-DD HH:mm:ss')
                    }
                    return item
                })
                setData(arr)
                return
            }
            message.error('很遗憾，修改失败，请稍后再试')
        } catch (_) { }
    }

    return <TaskStyle>
        <div className="header-box">
            <h2 className="title">TASK OA 任务管理系统</h2>
            <Button type="primary" onClick={() => setModalVisible(true)}>新增任务</Button>
        </div>

        <div className="tag-box">
            {['全部', '未完成', '已完成'].map((item, index) => {
                return <Tag key={index}
                    color={selectedIndex === index ? '#1677ff' : ''}
                    onClick={() => {
                        if (selectedIndex === index) return
                        setSelectedIndex(index)
                    }}>
                    {item}
                </Tag>
            })}
        </div>

        <Table columns={columns} dataSource={data} loading={loading} pagination={false} rowKey="id" size="middle" />

        <Modal title="新增任务窗口"
            okText="确认提交"
            keyboard={false}
            maskClosable={false}
            getContainer={false}
            confirmLoading={confirmLoading}
            open={modalVisible}
            afterClose={closeModal}
            onCancel={closeModal}
            onOk={submit}>

            <Form colon={false}
                layout="vertical"
                validateTrigger="onBlur"
                form={formIns}
                initialValues={{
                    task: '',
                    time: dayjs().add(1, 'day')
                }}>
                <Form.Item name="task" label="任务描述"
                    rules={[
                        { required: true, message: '任务描述是必填项' }
                    ]}>
                    <Input.TextArea rows={4} />
                </Form.Item>
                <Form.Item name="time" label="预期完成时间"
                    rules={[
                        { required: true, message: '请先选择预期完成时间' }
                    ]}>
                    <DatePicker showTime />
                </Form.Item>
            </Form>

        </Modal>
    </TaskStyle >
}